<template>
  <div class="react-app-container">
    <micro-app 
      name="react-app" 
      url="http://localhost:3002/" 
      :data="microAppData"
      @created="handleCreated"
      @beforemount="handleBeforeMount"
      @mounted="handleMounted"
      @unmount="handleUnmount"
      @error="handleError"
      inline
      clear-data
      destroy
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeUnmount } from 'vue'
import microApp from '@micro-zoe/micro-app'

const microAppData = ref({
  path: '/'
})

// 用于跟踪卸载状态
let isUnmounting = false

const handleCreated = (e: CustomEvent) => {
  console.log('micro-app-react created--', e.detail)
  // 重置卸载状态
  isUnmounting = false
  
  // 确保子应用环境变量正确设置
  // @ts-ignore
  window.__MICRO_APP_ENVIRONMENT__ = true
  // @ts-ignore
  window.__MICRO_APP_NAME__ = 'react-app'
  // @ts-ignore
  window.__MICRO_APP_PUBLIC_PATH__ = 'http://localhost:3002/'
}

const handleBeforeMount = () => {
  console.log('micro-app-react beforemount')
  // 确保容器存在
  const container = document.getElementById('root')
  if (!container) {
    const div = document.createElement('div')
    div.id = 'root'
    document.querySelector('.react-app-container')?.appendChild(div)
  }
}

const handleMounted = () => {
  console.log('micro-app-react mounted')
  // 延迟执行挂载，确保 DOM 已准备好
  setTimeout(() => {
    // 获取子应用实例
    // @ts-ignore
    const reactApp = window[`micro-app-react-app`]
    if (reactApp?.mount) {
      console.log('找到 React 子应用，执行挂载')
      reactApp.mount()
    } else {
      console.warn('未找到 React 子应用实例')
    }
  }, 16)
}

const handleUnmount = () => {
  // 避免重复卸载
  if (isUnmounting) {
    console.log('micro-app-react unmount already in progress')
    return
  }

  console.log('micro-app-react unmount start')
  try {
    isUnmounting = true
    const apps = microApp.getActiveApps()
    if (apps.find(app => app.name === 'react-app')) {
      microApp.unmountApp('react-app')
      console.log('micro-app-react unmount complete')
    } else {
      console.log('micro-app-react already unmounted')
    }
  } catch (e) {
    console.error('React 子应用卸载出错:', e)
  }
}

const handleError = (e: CustomEvent) => {
  console.error('micro-app-react error:', e.detail)
}

// 组件卸载前确保清理
onBeforeUnmount(() => {
  handleUnmount()
})
</script>

<style scoped>
.react-app-container {
  width: 100%;
  height: 100%;
  position: relative;
}
</style> 